package com.towexin.config.thymeleaf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.View;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * TODO
 * 自定义thymeleaf模板错误返回
 * @author Towexin
 * @version 1.0
 * @date 2021/6/9 10:10
 */
@Configuration
public class ThymeleafError {
    @Bean("error")
    public View defaultErrorView(){
        return new View() {
            @Override
            public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("text/html");
                PrintWriter out = response.getWriter();

                // 1. 创建模板解析器 并设置相关属性
                ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
                // 配置解析器模板存储文件夹路径
                resolver.setPrefix("template-model/");
                // 配置解析器模板文件后缀
                resolver.setSuffix(".html");

                // 通过template模板获取html内容
                TemplateEngine templateEngine = new TemplateEngine();
                templateEngine.setTemplateResolver(resolver);

                // 更新请求的页面的内容为404页面
                out.write(templateEngine.process("404", new Context()));
                out.close();
            }
            @Override
            public String getContentType() {
                return "text/html";
            }
        };
    }

}
